import requests
import pandas as pd
import json
from datetime import datetime, timedelta
import random
import numpy as np

class DataFetcher:
    """
    用于从网络API获取数据的类
    """

    @staticmethod
    def get_huizhou_temperature():
        """
        获取最近一个月惠州气温数据
        由于免费API限制，这里使用模拟数据
        实际应用中可替换为真实API调用
        """
        try:
            # 模拟最近30天的数据
            end_date = datetime.now()
            start_date = end_date - timedelta(days=30)

            dates = []
            temps_high = []
            temps_low = []

            current_date = start_date
            while current_date <= end_date:
                dates.append(current_date.strftime('%Y-%m-%d'))
                # 模拟惠州的气温范围 (春季约15-28°C)
                high_temp = round(random.uniform(22, 28), 1)
                low_temp = round(random.uniform(15, 21), 1)
                temps_high.append(high_temp)
                temps_low.append(low_temp)
                current_date += timedelta(days=1)

            df = pd.DataFrame({
                'date': dates,
                'high_temp': temps_high,
                'low_temp': temps_low
            })

            return df
        except Exception as e:
            print(f"获取惠州气温数据失败: {e}")
            return pd.DataFrame()

    @staticmethod
    def get_gold_price():
        """
        获取最近30天黄金价格趋势
        使用上海黄金交易所API或模拟数据
        """
        try:
            # 模拟最近30天的数据
            end_date = datetime.now()
            start_date = end_date - timedelta(days=30)

            dates = []
            prices = []

            # 起始价格约为2000美元/盎司
            base_price = 2000
            current_price = base_price

            current_date = start_date
            while current_date <= end_date:
                dates.append(current_date.strftime('%Y-%m-%d'))
                # 模拟每天的价格波动 (-1.5% 到 +1.5%)
                change = current_price * random.uniform(-0.015, 0.015)
                current_price += change
                prices.append(round(current_price, 2))
                current_date += timedelta(days=1)

            df = pd.DataFrame({
                'date': dates,
                'price': prices
            })

            return df
        except Exception as e:
            print(f"获取黄金价格数据失败: {e}")
            return pd.DataFrame()

    @staticmethod
    def get_china_pressure():
        """
        获取中国各地气压分布图数据
        使用气象API或模拟数据
        """
        try:
            # 中国主要城市及其大致经纬度
            cities = {
                '北京': (116.41, 39.90),
                '上海': (121.47, 31.23),
                '广州': (113.27, 23.13),
                '深圳': (114.06, 22.55),
                '成都': (104.07, 30.67),
                '重庆': (106.55, 29.56),
                '武汉': (114.31, 30.59),
                '西安': (108.95, 34.27),
                '南京': (118.78, 32.06),
                '杭州': (120.21, 30.25),
                '济南': (117.12, 36.65),
                '哈尔滨': (126.54, 45.80),
                '沈阳': (123.43, 41.81),
                '长春': (125.32, 43.82),
                '拉萨': (91.11, 29.97),
                '乌鲁木齐': (87.62, 43.82),
                '银川': (106.23, 38.47),
                '呼和浩特': (111.75, 40.84),
                '南宁': (108.37, 22.82),
                '海口': (110.32, 20.04),
                '昆明': (102.71, 25.04),
                '贵阳': (106.71, 26.57),
                '长沙': (112.98, 28.20),
                '南昌': (115.89, 28.68),
                '合肥': (117.23, 31.82),
                '福州': (119.30, 26.08),
                '台北': (121.52, 25.03),
                '兰州': (103.82, 36.06),
                '西宁': (101.78, 36.62),
                '太原': (112.55, 37.87)
            }

            # 生成模拟的气压数据 (通常在950-1050 hPa之间)
            data = []
            for city, (lon, lat) in cities.items():
                # 模拟气压值，春季中国大部分地区在1000-1020 hPa之间
                pressure = round(random.uniform(1000, 1020), 1)
                data.append({
                    'city': city,
                    'lon': lon,
                    'lat': lat,
                    'pressure': pressure
                })

            df = pd.DataFrame(data)
            return df
        except Exception as e:
            print(f"获取中国气压分布数据失败: {e}")
            return pd.DataFrame()

    @staticmethod
    def get_cny_exchange_rate():
        """
        获取离岸人民币汇率走势
        使用金融API或模拟数据
        """
        try:
            # 模拟最近30天的数据
            end_date = datetime.now()
            start_date = end_date - timedelta(days=30)

            dates = []
            rates = []

            # 起始汇率约为1美元=7.1人民币
            base_rate = 7.1
            current_rate = base_rate

            current_date = start_date
            while current_date <= end_date:
                dates.append(current_date.strftime('%Y-%m-%d'))
                # 模拟每天的汇率波动 (-0.3% 到 +0.3%)
                change = current_rate * random.uniform(-0.003, 0.003)
                current_rate += change
                rates.append(round(current_rate, 4))
                current_date += timedelta(days=1)

            df = pd.DataFrame({
                'date': dates,
                'rate': rates
            })

            return df
        except Exception as e:
            print(f"获取离岸人民币汇率数据失败: {e}")
            return pd.DataFrame()
